package com.radiant.servlet.filters;

import java.io.IOException;

import javax.inject.Inject;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.google.inject.Singleton;
import com.radiant.data.entity.User;
import com.radiant.exceptions.RadiantRuntimeException;
import com.radiant.service.UserAuthenticationService;
import com.radiant.service.UserService;

@Singleton
public final class AuthenticationFilter implements Filter 
{
	@Inject
	private UserAuthenticationService authService;
	
	@Inject
	private UserService userService;

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		
			HttpServletRequest req = (HttpServletRequest)request; 
	        String token = req.getParameter("token");
	        if (authService.validateToken(token)) {
	        	User user = authService.getUser(token);
	        	userService.setCurrentUser(user);
	        	try {
	        		chain.doFilter(request, response);
	        	} finally {
	        		userService.setCurrentUser(null);
	        	}
	        } else {
	        	throw new RadiantRuntimeException("Not authenticated");
	        }
	}
		
	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}
}